package com.android.basewars;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class LogInActivity extends Activity {
	private static final String HashPassString = null;
	EditText editLogIn, editPassword;
	Button buttonLogin, buttonRegister;
	boolean output;
	InputStream is = null;
	String result = "";
	JSONObject jArray = null;

	
 	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginview);
        
        setupViews();
        setListeners();
        
    }
 	
 	private void logIn() throws NoSuchAlgorithmException, UnsupportedEncodingException{
 		//output = false;
 		 String encodedpassword = convertMD5(editPassword.getText().toString());
 		getUser(editLogIn.getText().toString(),encodedpassword);
 	}
 	private void toRegister(){
 		Intent register = new Intent(getApplicationContext(), RegisterActivity.class);
 		startActivity(register);
 	}
	private void setListeners() {
		buttonLogin.setOnClickListener
    	( new View.OnClickListener(){@Override public void onClick(View v) {try {
			logIn();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}}});
		buttonRegister.setOnClickListener
    	( new View.OnClickListener(){@Override public void onClick(View v) {toRegister();}});
	}

	private void setupViews() {
		//Edittext
		editLogIn =			(EditText)findViewById(R.id.editTextLogIn);
		editPassword =		(EditText)findViewById(R.id.editTextPassword);
		
		//buttons
		buttonLogin = 		(Button)findViewById(R.id.buttonLogIn);
		buttonRegister =	(Button)findViewById(R.id.buttonNewRegister);
	}
	
	
	
	
	 public void getUser( String username, String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		 	
		
		 HttpClient httpclient = new DefaultHttpClient();
		 HttpPost httppost = new HttpPost("http://frankkie.nl/basewars/api/v4/login");
		   
		    try{
		        // Add your data
		        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		        nameValuePairs.add(new BasicNameValuePair("username", username));
		        nameValuePairs.add(new BasicNameValuePair("password", "9fbbd3fb9e05ad08dbdd1792d663c4fa0a18b20")); //TODO
		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	
		        // Execute HTTP Post Request
		        HttpResponse response = httpclient.execute(httppost);

		        
		        HttpEntity entity = response.getEntity();
		        is = entity.getContent();
		        
		        try{
		        	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		        	        StringBuilder sb = new StringBuilder();
		        	        String line = null;
		        	        while ((line = reader.readLine()) != null) {
		        	            sb.append(line + "\n");
		        	        }
		        	      is.close();
		        	        result=sb.toString();
		        	        handleMessageLogin(result);
		        	    }catch(Exception e){
		        	       // Log.e("log_tag", "Error converting result "+e.toString());
		        	
		        	    }


		    }catch (ClientProtocolException e) {
		        // TODO Auto-generated catch block
		    } catch (IOException e) {
		        // TODO Auto-generated catch block
		    }
		    
		 
		 
	 
		/*    Handler handler = new Handler() {
				
				;
			new HttpConnection(handler)
					.get("http://frankkie.nl/basewars/api/v4/User/" + username);
			
			*/
			
	 	}
		    
		public void handleMessageLogin(String response) {
					try {
						
						JSONObject json_user = new JSONObject(response);
						boolean b = json_user.getBoolean("success");
						if(b){
							
							JSONObject user = json_user.getJSONObject("result");
							int id =  Integer.parseInt(user.getString("id"));
					 		Intent login = new Intent(getApplicationContext(), BaseWarsActivity.class);
							//Intent login = new Intent(getApplicationContext(), AttackLogActivity.class);
					 		login.putExtra("userid", id);
					 		startActivity(login);
					 		finish();
				 			}else{
				 				editLogIn.setError("Inlog FOUT!");
				 			}
						}
					catch (JSONException e) {
						e.printStackTrace();
					}
			
		}
	 
	 public String convertMD5(String s){
	        try {
	            // Create MD5 Hash
	            MessageDigest digest = java.security.MessageDigest.getInstance("SHA1");
	            digest.update(s.getBytes());
	            byte messageDigest[] = digest.digest();
	            
	            // Create Hex String
	            StringBuffer hexString = new StringBuffer();
	            for (int i=0; i<messageDigest.length; i++)
	                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
	            return hexString.toString();
	            
	        } catch (NoSuchAlgorithmException e) {
	            e.printStackTrace();
	        }
	        return "";
		}

}


